import { isNullOrWhiteSpece } from './is';

/**
 * @param str 需要转下划线的驼峰字符串
 * @returns 字符串下划线
 */
export const humpToUnderline = (str: string): string => {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase();
};

/**
 * @param str 需要转驼峰的下划线字符串
 * @returns 字符串驼峰
 */
export const underlineToHump = (str: string): string => {
  return str.replace(/\-(\w)/g, (_, letter: string) => {
    return letter.toUpperCase();
  });
};

export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  dom.style.setProperty(prop, val);
};

/**
 * 查找数组对象的某个下标
 * @param {Array} ary 查找的数组
 * @param {Functon} fn 判断的方法
 */

export const findIndex = <T = Recordable>(ary: Array<T>, fn: any): number => {
  if (ary.findIndex) {
    return ary.findIndex(fn);
  }
  let index = -1;
  ary.some((item: T, i: number, ary: Array<T>) => {
    const ret: T = fn(item, i, ary);
    if (ret) {
      index = i;
      return ret;
    }
    return false;
  });
  return index;
};

export const trim = (str: string) => {
  return str.replace(/(^\s*)|(\s*$)/g, '');
};

/**
 * @param {Date | number | string} time 需要转换的时间
 * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
 */
export function formatTime(time: Date | number | string, fmt: string) {
  if (!time) {
    return '';
  }

  const date = new Date(time);
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
    }
  }
  return fmt;
}

/**
 * 生成随机字符串
 */
export function toAnyString() {
  const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
    const r: number = (Math.random() * 16) | 0;
    const v: number = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString();
  });
  return str;
}

/**
 * 根据对象字段类填充数据
 * @param target 需要填充数据的对象
 * @param Obj 用类填充的对象(有数据)
 * @param force 源对象有数据时是否强制填充,
 */
export function fillObjByObj<T>(target, Obj, force = false): T {
  if (target && Obj) {
    Object.keys(target).forEach((key) => {
      // 不强制填充 并且 对象不为空, 则退出;
      if (!force && !isNullOrWhiteSpece(target[key])) {
        return;
      }
      if (key in Obj) {
        if (Obj[key] === null) {
          target[key] = null;
        } else if (typeof Obj[key] === 'object') {
          target[key] = cloneObj(Obj[key]);
        } else {
          target[key] = Obj[key];
        }
      }
    });
  }
  return target;
}

export function mapGetData<T>(target, Obj): T {
  return fillObjByObj(target, Obj, true);
}

export function cloneObj(obj): any {
  let newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object') {
    return;
  } else if (JSON) {
    newobj = JSON.parse(JSON.stringify(obj)); // 还原
  } else {
    Object.keys(obj).forEach((key) => {
      newobj[key] = typeof obj[key] === 'object' ? cloneObj(obj[key]) : obj[key];
    });
  }
  return newobj;
}

/**
 * 待优化
 * @param obj
 */
export function deepClone(obj): any {
  let newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object') {
    return;
  } else if (JSON) {
    newobj = JSON.parse(JSON.stringify(obj)); // 还原
  } else {
    Object.keys(obj).forEach((key) => {
      newobj[key] = typeof obj[key] === 'object' ? cloneObj(obj[key]) : obj[key];
    });
  }
  return newobj;
}
